//
//  DestinationTripViewController.m
//  HappyTrip
//
//  Created by yuxuesong on 15-3-24.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "DestinationTripViewController.h"
#import "DestinationTripTableViewCell.h"
#import "DesTripsObject.h"
#import "TravelNoteViewController.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"

#define TABELRESUE @"tripViewTableViewReuse"

@interface DestinationTripViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain)NSMutableArray *tripArr;
@property (nonatomic, retain)UITableView *tripTableView;
@property (nonatomic, retain)DesTripsObject *desTripsObj;
@property (nonatomic, retain)MBProgressHUD *progressHUD;

@end

@implementation DestinationTripViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:170.0 / 255.0 blue:205.0 / 255.0 alpha:1.0];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorWithRed:250.0 / 255.0 green:240.0 / 255.0 blue:220.0 / 255.0 alpha:1.0];
    self.title = @"游记";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];

    self.tripArr = [NSMutableArray array];
    [self handleData:0];
    
    self.tripTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT + 49) style:UITableViewStylePlain];
    _tripTableView.delegate = self;
    _tripTableView.dataSource = self;
    [self.tripTableView registerClass:[DestinationTripTableViewCell class] forCellReuseIdentifier:TABELRESUE];
    _tripTableView.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    _tripTableView.separatorStyle = NO;
    [self.view addSubview:_tripTableView];
    [_tripTableView release];
    
    //转菊花
    self.progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
    _progressHUD.labelText = @"请稍等...";
    _progressHUD.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_progressHUD];
    [_progressHUD release];
    [_progressHUD show:YES];
    
    //刷新加载
    [_tripTableView addLegendHeaderWithRefreshingBlock:^{
        [self handleData:0];
    }];
    [_tripTableView addLegendFooterWithRefreshingBlock:^{
        static NSInteger i = 1;
        [self handleData:i++ * 20];
    }];
}
#pragma mark - UITableView 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tripArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DestinationTripTableViewCell *tripCell = [tableView dequeueReusableCellWithIdentifier:TABELRESUE];
    tripCell.imageView.layer.cornerRadius = 20;
    tripCell.imageView.clipsToBounds = YES;
    tripCell.selectionStyle = UITableViewCellSelectionStyleNone;
    tripCell.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    tripCell.desTripsObject = [self.tripArr objectAtIndex:indexPath.row];
    return tripCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (self.view.frame.size.height + 49) / 4;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelNoteViewController *travelVC = [[TravelNoteViewController alloc] init];
    DesTripsObject *desTrips = [self.tripArr objectAtIndex:indexPath.row];
    travelVC.transmitId = [desTrips.idNumber stringValue];
    [self.navigationController pushViewController:travelVC animated:YES];
    [travelVC release];
}

#pragma mark - 返回按钮
- (void)leftBarButtonItemAction:(UIBarButtonItem *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)handleData:(NSInteger)number
{
    NSString *urlStr =[NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/trips/?start=%ld&count=20", self.tripsSendType, self.tripsSendId, number];
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%ld.happyTripCountryTrips", docPath, [urlStr hash]];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:path];
        NSLog(@"存储成功: %d", result);
        NSMutableArray *itemsArr = [NSMutableArray array];
        itemsArr = [responseObject objectForKey:@"items"];
        for (NSMutableDictionary *dic in itemsArr) {
            DesTripsObject *desTrips = [[DesTripsObject alloc] initWithDic:dic];
            [self.tripArr addObject:desTrips];
            [desTrips release];
        }
        [self.tripTableView reloadData];
        [_progressHUD removeFromSuperview];
        [_tripTableView.header endRefreshing];
        [_tripTableView.footer endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        id resultID = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSMutableArray *itemsArr = [NSMutableArray array];
        itemsArr = [resultID objectForKey:@"items"];
        self.tripArr = [NSMutableArray array];
        for (NSMutableDictionary *dic in itemsArr) {
            DesTripsObject *desTrips = [[DesTripsObject alloc] initWithDic:dic];
            [self.tripArr addObject:desTrips];
            [desTrips release];
        }
        [self.tripTableView reloadData];
        [_progressHUD removeFromSuperview];
        [_tripTableView.header endRefreshing];
        [_tripTableView.footer endRefreshing];
        static NSInteger i = 1;
        if (1 == i) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络不给力,请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        }
        i++;
    }];
}

- (void)dealloc
{
    [_tripTableView release];
    [_tripArr release];
    [_desTripsObj release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
